import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpRequest } from "../../../../service/httpRequest";
import { NotiService } from "../../../../service/noti.service";
import { FileLoader } from "../../../../service/fileLoader";
import { Http, Response, Headers, RequestOptions,URLSearchParams } from '@angular/http';

declare let $:any;
@Component({
  selector: 'comparedata',
  templateUrl: './comparedata.component.html',
  styleUrls: ['./comparedata.component.css']
})
export class ComparedataComponent implements OnInit {

  public deviceIds:any;
  public devdata:any[];
  public devids = [];
  public proids = [];
  propertyData:any;
  public tdata:any;
  public paradata:Object={};

  constructor(private activeRoute:ActivatedRoute,private http:Http,private noti:NotiService,private fileLoader:FileLoader,private httpRequest:HttpRequest,) { }

  ngOnInit() {
    this.fileLoader.LoadFileList(['assets/js/button.js'], function(){});
    this.activeRoute.params.subscribe(
      params=>{
        //console.log(params);
        this.deviceIds = params['deviceIds'].split(',');        
      }
    );


    for(let i=0;i<this.deviceIds.length;i++){
      let devid = this.deviceIds[i].replace('|','/'); 
      this.devids.push(devid);
      this.proids.push(devid.split('/')[0]);      
    }
    
    this.getDevicedata();
    this.getProperty();
    this.initDatePicker()
    

  }

  unique(arr){    
    let tmp = new Array();
    for(let i in arr){    
      if(tmp.indexOf(arr[i])==-1){
        tmp.push(arr[i]);
      }
    }
    return tmp;
  }
//devinfo
  getDevicedata(){ 
    //console.log(this.devids)   
    this.httpRequest.sendGet('devices',{id:this.devids.join(',')}).subscribe(res => {
      this.devdata = res.result;
     // console.log(res.result)
    },err => console.log(err));
  }

  //数据点数据
  getProperty(){  
    this.proids = this.unique(this.proids);  
    console.log(this.proids)
    this.httpRequest.sendGet('product/property/list/'+this.proids.join(',')).subscribe(res => {      
      this.propertyData = res.result;     
    },err => console.log(err));
  }

  //时间插件的初始化
  initDatePicker(){
    $(".form_datetime").datetimepicker({
            format: "yyyy-mm-dd hh:ii",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 30 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date()  
      });
      
  }

//查询历史数据
   public count = 0;   
   public selectedproperty:any = {};
   fn($event,property){  
     let checkbox = $event.target; 
        if (checkbox.checked) {
            this.count++;
            this.selectedproperty[property]=property;
        }else{
            this.count--;
            delete this.selectedproperty[property];
        }                
      if(this.count>5){
        alert("对不起，每次展示参数最多可以选择5个！");
        checkbox.checked = false;
        this.count=5;
      }             
    }         

 
    chosedparam(){        
      let properties = [];
      let btn = $("#myButton").button('loading') 
      for(let key in this.selectedproperty){
        properties.push(key)
      }
      let str = properties.join(',')
      let sdate = $('#stime').val(); 
      //console.log(sdate) 
       //console.log(str) 
      if(str!=''&&sdate!=''){
          let headers = new Headers();
          let authToken = localStorage.getItem("token");
          headers.append('Authorization', `token ${authToken}`);
          let options = new RequestOptions({ headers: headers }); 
          this.http.post('http://101.37.24.73:8088/multiple_history30',{
            device_id:this.devids.join(','),
            sdate:sdate,
            parameter:str
          },options).subscribe(res=>{
            //console.log(res.json())            
            btn.button('reset');       
            let gh30data = res.json().result.aaData;
            this.tdata = res.json().result.aaData;
            this.paradata={};
            for(let i=0;i<gh30data.length;i++){
              let qxdata = gh30data[i].Data;
              let mid = gh30data[i].parameter;              
              this.paradata['parameter'+i] = mid;
              this.getqxdata(mid,qxdata);
            }
             this.http.post('http://101.37.24.73:8088/multiple_history30',{
                device_id:this.devids.join(','),
                sdate:sdate,
                parameter:str
              },options).subscribe(res=>{                           
                btn.button('reset');       
                let gh30data = res.json().result.aaData;
                this.tdata = res.json().result.aaData;
                for(let i=0;i<gh30data.length;i++){
                  let qxdata = gh30data[i].Data;
                  let mid = gh30data[i].parameter;
                  this.paradata['parameter'+i] = mid;
                  this.getqxdata(mid,qxdata); 
                }
              },err=>{
                alert('查询失败');
                btn.button('reset'); 
              })

          },err=>{
            alert('查询失败');
            btn.button('reset'); 
          })    
          
      }else{
        alert('请选择参数或者时间');
        btn.button('reset'); 
      }      
     
  
    }  

 
getqxdata(id,data){ 
  //console.log(id)
  $('#'+id).highcharts({
    chart: {
        type: 'spline'
    },
    title: {
        text: '参数的历史数据曲线'
    },
    
    xAxis: {
        type: 'datetime',
        labels: {
            overflow: 'justify'
        }
    },
    yAxis: {
        title: {
            text: '参数值'
        },
        minorGridLineWidth: 0,
        gridLineWidth: 0,
        alternateGridColor: null,
    
    },
    tooltip: {
        valueSuffix: ''
    },
    plotOptions: {
        spline: {
            lineWidth: 2,
            states: {
                hover: {
                    lineWidth: 3
                }
            },
            marker: {
                enabled: false
            },
            pointInterval: 3600000, // one hour
            pointStart: Date.UTC(2015, 4, 31, 0, 0, 0)
        }
    },
    series: data,
    navigation: {
        menuItemStyle: {
            fontSize: '10px'
        }
    }
});
}


  

  

}
